// api/index.js
import Mock from 'mockjs'
const BASE_URL = 'https://api.example.com' // 替换为你的后端接口地址

// 创建请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    if (!options.url) {
      reject(new Error('请求地址不能为空'))
      return
    }


    // 使用 mockjs 模拟数据
    if (options.url === '/api/books') {
      console.log(Mock.Random.name())

      const data = Mock.mock({
        code: 200,
        'data|1-10': [{
          'id|+1': 1,
          'title|4-8': Mock.Random.title()||'标题', // 生成随机标题
          cover: Mock.Random.image('200x300', '#894FC4', '#FFF', 'png', '标题'), // 生成随机图片
          // 'name': '@name',
          // 'age|20-30': 1,
          // 'city': '@city'
        }]

      })
      console.log(data, 'mock data')

      resolve(data)
      return
    }

    uni.request({
      ...options,
      url: `${BASE_URL}${options.url}`,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 请求拦截器
const beforeRequest = (options) => {
  // 可以在这里添加统一的请求头、token等
  const token = uni.getStorageSync('user_token') // 假设 token 存储在本地存储中
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    }
  }
  return options
}

// 响应拦截器
const afterResponse = (response) => {
  // 可以在这里统一处理响应数据
  return response
}

// 封装请求方法
const api = {
  get: (url, data = {}) => {
    const options = beforeRequest({ url, method: 'GET', data })
    return request(options).then(afterResponse)
  },
  post: (url, data = {}) => {
    const options = beforeRequest({ url, method: 'POST', data })
    return request(options).then(afterResponse)
  },
  put: (url, data = {}) => {
    const options = beforeRequest({ url, method: 'PUT', data })
    return request(options).then(afterResponse)
  },
  delete: (url, data = {}) => {
    const options = beforeRequest({ url, method: 'DELETE', data })
    return request(options).then(afterResponse)
  }
}

export default api

const booksApi = {
  async getBooks() {
    return api.get(
      "/api/books"
    )
  },
  async getBookDetail(bookId) {
    return uni.request({
      url: `/api/books/${bookId}`,
      method: "GET"
    })
  },
  async getChapters(bookId) {
    return uni.request({
      url: `/api/books/${bookId}/chapters`,
      method: "GET"
    })
  },
  async getChapterContent(chapterId) {
    return uni.request({
      url: `/api/chapters/${chapterId}/content`,
      method: "GET"
    })
  }
}